package bg.cinema_system.DAO;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import bg.cinema_system.beans.MovieBean;

public class MovieDAO {

	private long movie_id;
	private DataSource dataSource;

	public MovieDAO(long movie_id, DataSource dataSource) {
		this.movie_id = movie_id;
		this.dataSource = dataSource;
	}

	// Connect to DB and get information about the selected Movie
	public MovieBean getMovie() throws SQLException {
		// Check if there is such DataSource
		if (dataSource == null) {
			throw new SQLException("Class MovieDAO: Can't get data source");
		}

		// Get database connection
		Connection dbConnection = dataSource.getConnection();

		if (dbConnection == null) {
			throw new SQLException(
					"Class MovieDAO: Can't get database connection");
		}

		String sqlStatement = "SELECT movies.movie_id, movies.name, movies.movie_type, movies.duration, movies.director, movies.actors, movies.country, movies.summary "
				+ "FROM movies " + "WHERE movies.movie_id = '" + movie_id + "'";

		PreparedStatement ps = dbConnection.prepareStatement(sqlStatement);

		// Get customer data from database
		ResultSet result = ps.executeQuery();

		MovieBean movie = new MovieBean();

		while (result.next()) {
			movie.setMovie_id(result.getLong("movie_id"));
			movie.setName(result.getString("name"));
			movie.setMovie_type(result.getString("movie_type"));
			movie.setDuration(result.getTime("duration"));
			movie.setDirector(result.getString("director"));
			movie.setActors(result.getString("actors"));
			movie.setCountry(result.getString("country"));
			movie.setSummary(result.getString("summary"));
		}

		return movie;
	}
}
